$(document).ready(init);
$(document).ready(init_login);

function init() { 
	var ds = new dataSuggestions();

	ds.data = cities;	//FIX HERE to get the proper array of elements

	var oTextbox = new AutoSuggestControl(document.getElementById("txt1"), ds);  // HTML Searchbox id = txt1
	var input = $('#txt1');
	var original = input.val();

	var submit = function(){
				submitdata = {  'value' : this.val(),
								'lat': citylatlng[this.val().toUpperCase()][0],
								'lng': citylatlng[this.val().toUpperCase()][1] };
	
				$.ajax({
					type	: 'GET',
					url		: 'changeloc/',
					data	: submitdata,
					success	: function(response){
									$('#deals').html(response);
									init();}
				});

				this.blur();
				this.val("Saving...");

	};

	oTextbox.createDropDown(submit); //call this after submit is defined (hack)

	var onKeyUp = function(e) {
			if (e.keyCode == 27) {
				input.blur();
			}
			if(e.keyCode == 13) {
				submit.apply(input);
			}
	};
	var onMouseOver = function(e){
			input.css('background-color','yellow')
				 .css('border','1px inset');
	};
	var onMouseOut = function(e){
			input.css('background-color','white')
				 .css('border','0px');
	};
	var onFocus = function(e){
		input.css('background-color','white')
			 .css('border','1px inset')
			 .unbind('mouseover')
			 .unbind('mouseout')
			 .select();
	};
	var onBlur = function(e){ 
		input.val(original)
			 .css('background-color','white')
			 .css('border','0px')
			 .bind({'mouseover': onMouseOver,
					'mouseout': onMouseOut});
	};

	input.bind({'keyup': onKeyUp,
				'mouseover': onMouseOver,
				'mouseout': onMouseOut,
				'focus': onFocus,
				'blur': onBlur});
}

$('html').ajaxSend(function(event, xhr, settings) {
    function getCookie(name) {
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
    if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
        // Only send the token to relative URLs i.e. locally.
        xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
    }
});
